package edu.gyc.hivhr.auth;

import com.fasterxml.jackson.databind.ObjectMapper;
import edu.gyc.hivhr.auth.CustomeUrlDecisionManager;
import edu.gyc.hivhr.auth.CustomFilterInvocationSecurityMetadataSource;
import edu.gyc.hivhr.model.Hr;
import edu.gyc.hivhr.model.ResultBean;
import edu.gyc.hivhr.service.HrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

   @Autowired
    private HrService hrService;

   @Autowired
   private CustomFilterInvocationSecurityMetadataSource securityMetadataSource;

   @Autowired
   private CustomeUrlDecisionManager decisionManager;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       // auth.userDetailsService(hrService).passwordEncoder(new BCryptPasswordEncoder());
        auth.userDetailsService(hrService);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/login");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //.anyRequest().authenticated()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O o) {

                        o.setAccessDecisionManager(decisionManager);
                        o.setSecurityMetadataSource(securityMetadataSource);
                        return  o;
                    }
                })
                .and()
                .formLogin()
                .usernameParameter("username")
                .passwordParameter("password")
                .loginProcessingUrl("/doLogin")
                .loginPage("/login")
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                                        Authentication authentication) throws IOException, ServletException {
                        response.setContentType("application/json;charset=utf-8");
                        PrintWriter out=response.getWriter();
                        Hr hr = ((Hr) authentication.getPrincipal());
                       ResultBean resultBean= ResultBean.ok("登录成功",hr);
                        out.write(new ObjectMapper().writeValueAsString(resultBean));
                        out.flush();
                        out.close();
                    }
                })
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                                        AuthenticationException e) throws IOException, ServletException {
                        response.setContentType("application/json;charset=utf-8");
                        PrintWriter out=response.getWriter();
                        ResultBean resultBean = ResultBean.error("登录失败");
                        if (e instanceof LockedException) {
                            resultBean.setMsg("账号被锁定，请联系管理员");
                        } else if (e instanceof CredentialsExpiredException) {
                            resultBean.setMsg("密码过期，请联系管理员");
                        } else if (e instanceof AccountExpiredException) {
                            resultBean.setMsg("账号过期，请联系管理员");
                        } else if (e instanceof DisabledException) {
                            resultBean.setMsg("账号被禁用，请联系管理员");
                        } else if (e instanceof BadCredentialsException) {
                            resultBean.setMsg("用户名或者密码错误！");
                        }
                        out.write(new ObjectMapper().writeValueAsString(resultBean));
                        out.flush();
                        out.close();
                    }
                })
                .permitAll()
                .and()
                .logout()
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

                    }
                })
                .permitAll()
                .and()
                .csrf().disable();
    }
}
